<?php

namespace app\common\controller;


use Firebase\JWT\JWT;
use OSS\OssClient;
use sms\Sms;
use sreeb\Curl;
use think\facade\Env;

class CommonService
{
    private static $jwtKey = 'limashengqian';

    private static $returnMsg = [
        0 => '服务器内部错误！',
        1 => '账号不存在！',
        2 => '账号或密码错误！',
        3 => '短信发送失败，请勿频繁发送短信，或联系管理员解决！',
        4 => '超过每日发送短信上限！',
        5 => '验证码错误！',
        6 => '手机号不存在！',
        7 => '不存在的激活码！',
        8 => '合伙人已存在！',
        9 => '该码已被使用！',
        10 => '账号已被禁用！',
        11 => '账号尚未激活，请先激活！',
        12 => '账号状态未知错误！',
        13 => '激活码已失效！',
        14 => '错误的激活码！',
        15 => '上传文件错误！',

        100 => '该用户已经是合伙人了，请勿重复添加！',
        101 => '该用户是超级合伙人，不能添加！',
        102 => '请设置正确的比例！',
        103 => '已是禁用状态！',
        104 => '已是启用状态!',
        105 => '两次密码不一致！',
        106 => '修改成功！',
        107 => '添加成功！',
        108 => '新密码与旧密码一致！'
    ];


    public static function error($msg, $data = array(), $code = 0)
    {
        if (isset(self::$returnMsg[$msg])) {
            $msg = self::$returnMsg[$msg];
        }
        $response['msg'] = $msg;
        $response['data'] = $data;
        $response['code'] = $code;
        return json($response);
    }

    public static function success($data, $msg = '', $code = 200)
    {
        if (isset(self::$returnMsg[$msg])) {
            $msg = self::$returnMsg[$msg];
        }
        $response['msg'] = $msg;
        $response['data'] = $data;
        $response['code'] = $code;
        return json($response);
    }


    /**
     *
     * @param $tel
     * @param $templateParam //模板变量 ['code=>$code]
     * @param string $templateCode 模板名
     * @param string $signName 签名
     * @return bool
     */
    public static function sendSms($tel, $templateParam, $templateCode = 'SMS_175535973', $signName = '立马省钱')
    {
        $sms = new Sms();
        $res = $sms->sendSms($tel, $templateParam, $templateCode, $signName);
        if (isset($res->Code) && $res->Code == 'OK') {
            return true;
        }
        return false;
    }


    /**
     * jwt编码
     * iss: jwt签发者
     * sub: jwt所面向的用户
     * aud: 接收jwt的一方
     * exp: jwt的过期时间，这个过期时间必须要大于签发时间
     * nbf: 定义在什么时间之前，该jwt都是不可用的.
     * iat: jwt的签发时间
     * jti: jwt的唯一身份标识，主要用来作为一次性token,从而回避重放攻击。
     * @param array $payload
     * @param bool $expTime //过期时间
     * @return string
     */
    public static function jwtEncode(array $payload, $expTime = false)
    {
        if ($expTime) {
            $payload = array_merge(['exp' => $expTime], $payload);
        }
        return JWT::encode($payload, self::$jwtKey);
    }

    /**
     * jwt解码
     * @param $token
     * @return object
     */
    public static function jwtDecode($token)
    {
        return JWT::decode($token, self::$jwtKey, array('HS256'));
    }


    /**
     * emoji转义
     * @param $str
     * @return string
     */
    public static function emoji_encode($str)
    {
        $strEncode = '';
        $length = mb_strlen($str, 'utf-8');
        for ($i = 0; $i < $length; $i++) {
            $_tmpStr = mb_substr($str, $i, 1, 'utf-8');
            if (strlen($_tmpStr) >= 4) {
                $strEncode .= '[[EMOJI:' . rawurlencode($_tmpStr) . ']]';
            } else {
                $strEncode .= $_tmpStr;
            }
        }
        return $strEncode;
    }

    /**
     * emoji反转义
     * @param $str
     * @return string|string[]|null
     */
    public static function emoji_decode($str)
    {
        $strDecode = preg_replace_callback('|\[\[EMOJI:(.*?)\]\]|', function ($matches) {
            return rawurldecode($matches[1]);
        }, $str);
        return $strDecode;
    }


    /**
     * 通过IP获取IP归属地
     * @param bool $ip
     * @return false|string
     */
    public static function getAttributionByIp($ip = null)
    {
        if (!$ip) {
            $ip =  \ request()->ip();
        }
        $result = Curl::getInstance()->setTimeout(3, 3)->get('http://whois.pconline.com.cn/ip.jsp?ip=' . $ip)->send();
        return mb_convert_encoding($result->getBody(),"UTF-8","GBK");
    }


    /**
     * 获取请求的浏览器
     * @param null $header
     * @return mixed|string
     */
    public static function getBrowserInfo($header = null)
    {
        if (!$header) {
            $header = \request()->header();
        }
        $agent = !empty($header['HTTP_USER_AGENT']) ? $header['HTTP_USER_AGENT'] : '未知浏览器';
        return $agent;
    }


    /**
     * 上传文件到OSS
     * @param $filePath
     * @param $object //oss对应文件路径
     * @return bool
     * @throws \OSS\Core\OssException
     */
    public static function uploadOss($filePath, $object)
    {
        $accessKeyId = Env::get('oss.accessKeyId');
        $accessKeySecret = Env::get('oss.accessKeySecret');
        $endpoint = "oss-cn-hangzhou.aliyuncs.com";
        $bucket = "limashengqian";
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $res = $ossClient->uploadFile($bucket, $object, $filePath);

        return !empty($res['oss-request-url']) ? str_replace('http:', 'https:', $res['oss-request-url']) : false;
    }


}
